/* arch/x86/init/head32.S 
 * 
 * Copyright (C) 2021, 2022 intirain. 
 * 
 * This file is part of evx. 
 * 
 * evx is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * evx is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with evx. If not, see <https://www.gnu.org/licenses/>
 */ 




.code32


.globl _start

_start:
	/* we are now in the protected-mode, just 
	 * do some initializes, and call main */
	
	lgdt gdt_descr
	call init_idt

	movl $0xc0000000, %eax
	leal 1f, %ecx

	orl %ecx, %eax

	pushl %eax

	movl $0xc0000000, %eax
	leal init, %ecx

	orl %ecx, %eax

	pushl %eax

	retl

1:	hlt
	jmp 1b


init_idt:
	/* edx: high 32  eax: low 32 */
	leal default_int_handler, %edx

	/* KERNEL_CS */
	movl %edx, %eax
	andl $0x0000ffff, %eax
	addl $(8 << 16), %eax

	andl $0xffff0000, %edx
	addl $0x8e00, %edx

	movl $256, %ecx

	leal idt, %edi

rsidt: 	movl %eax, (%edi)
	movl %edx, 4(%edi)

	addl $8, %edi
	decl %ecx

	jnz rsidt

	lidt idt_descr
	ret


default_int_handler:
	incl 0xb8000
	iretl

.globl ret_intr

ret_intr:
	popl %eax
	movl %eax, %gs

	popl %eax
	movl %eax, %fs

	popl %eax
	movl %eax, %es

	popl %eax
	movl %eax, %ds

	popl %edi
	popl %esi
	popl %ebp
	popl %edx
	popl %ebx
	popl %ecx
	popl %eax

	addl $4, %esp

	iretl
	


.globl __stack_chk_fail, __stack_chk_fail_local
.globl die

__stack_chk_fail_local:
__stack_chk_fail:
die:
	hlt
	jmp __stack_chk_fail


.data

.align 16

.globl gdt

gdt:	.long 0x00000000, 0x00000000
	.long 0x0000ffff, 0x00cf9a00
	.long 0x0000ffff, 0x00cf9200


.globl gdt_descr

gdt_descr:
	.word . - gdt
	.long gdt

.align 16

.globl idt

idt: 	.fill 256, 8, 0

.globl idt_descr

idt_descr:
	.word . - idt
	.long idt
	


